import { Button, Col, Form, Input, Modal, Pagination, Row, Select, Table, TreeSelect, message } from 'antd'
import React, { useEffect, useState } from 'react'

import * as roles from '../../../api/base/roles';
import { list as menuList } from '../../../api/base/menus'
import useBseGeneraHook from '../../../components/BaseGeneraForm/hook';

const Roles: React.FC = () => {
  const { open, edit, rowId, openModal, closeModal, addModal, editModal, rowIdSelect, formRef } = useBseGeneraHook()
  const [form] = Form.useForm();
  const [total, setTotal] = useState<number>(0)
  const [list, setList] = useState<any[]>([])
  const [menu, setMenu] = useState<any[]>([])
  const [menuIds, setMenuIds] = useState<any[]>([]) // 存放菜单id


  const getList = async () => {
    const res = await roles.list().catch(err => console.log(err))
    setList(res.data.content)
    setTotal(res.data.totalElements)
  }

  const getMenu = async () => {
    const menus = await menuList().catch(err => console.log(err))
    setMenu(menus.data)
  }



  useEffect(() => {
    getList()
    getMenu()
  }, [])

  const onFinish = async (value: any) => {
    value.menuIds = menuIds
    let res = null
    if (edit) {
      res = await roles.created(value).catch(err => console.log(err))
    } else {
      res = await roles.update(rowId as number, value).catch(err => console.log(err))
    }
    if (res.success) {
      message.success('操作成功')
      getList()
      closeModal()
    }
  }
  const onChange = () => { }

  const onSelectChange = (value: any) => {
    const id = getMenusIds(menu, value).map(item => item.id)
    const pId = getMenusIds(menu, value).map(item => item.parent_id)
    setMenuIds([...id, ...Array.from(new Set(pId)).filter(item => item > 0)])
  }

  const getMenusIds = (menus: any[], value: any[]) => {
    const arr: any[] = []
    menus.forEach(item => {
      if (value.includes(item.id)) {
        arr.push(item)
      }
      if (item.children) {
        arr.push(...getMenusIds(item.children, value))
      }
    })
    return arr
  }


  const add = () => {
    openModal()
    addModal()
    formRef.current?.resetFields();
  }
  const rowEdit = async (record: any) => {
    openModal()
    editModal()
    rowIdSelect(record.id)
    const res = await roles.detail(record.id).catch(err => console.log(err)) as any
    const menuIds = res.data.menus.filter(i => i.node_type > 0).map(i => i.id)
    setMenuIds(res.data.menus.map(i => i.id))
    form.setFieldsValue({ ...res.data, menuIds, id: record.id })
  }

  const del = async (val: any) => {
    Modal.confirm({
      title: '确定删除',
      icon: null,
      okText: '是',
      cancelText: '否',
      onOk() {
        roles.del(val.id).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  return (
    <>
      <Button type="primary" onClick={add}>添加</Button>
      <div>
        <Table dataSource={list} pagination={false} rowKey="id"
          columns={[
            {
              title: '名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '操作',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <Button type="primary" onClick={() => rowEdit(record)}>编辑</Button>
                  <>&nbsp;</>
                  {/* <Button type="primary" onClick={() => del(record)}>删除</Button> */}
                </>
              ),
            },
          ]}
        />
      </div>

      <div><Pagination showSizeChanger={true} total={total} onChange={onChange} /></div>

      <Modal title={edit ? '添加' : '查看'} open={open} footer={null} onCancel={() => closeModal()}>
        <Form form={form} onFinish={onFinish} ref={formRef}>
          <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入角色名称' }]}>
            <Input placeholder="请输入角色名称" />
          </Form.Item>


          <Form.Item label="目录" name="menuIds" rules={[{ required: true, message: '请选择层级目录' }]}>
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={menu}
              placeholder="请选择目录"
              treeCheckable={true}
              fieldNames={{ label: 'name', value: 'id' }}
              treeDefaultExpandAll={!edit}
              showSearch={true}
              allowClear
              value={menuIds}
              onChange={onSelectChange}
            />
          </Form.Item>



          <Form.Item >
            <Row>
              <Col span={12}>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </Col>
              <Col span={12}>
                <Button onClick={() => closeModal()}>
                  取消
                </Button>
              </Col>
            </Row>
          </Form.Item>

        </Form>


      </Modal>
    </>
  )
}

export default Roles
